package collection

import (
	"encoding/json"
	"fmt"
)

func MapTest() {
	m1 := make(map[string]int)
	fmt.Println(m1)
	m1["a"] = 1
	m1["b"] = 2
	m1["c"] = 3
	m1["a"] = 100
	fmt.Println(m1)

	var m2 = map[string]int{"a": 1, "b": 2, "c": 3}
	fmt.Println(m2)

	//map如果不初始化，则nil
	var m3 map[string]string
	if m3 == nil {
		fmt.Println("nil map")
	}
	m3 = make(map[string]string)
	m3["pc"] = "amd"
	m3["phone"] = "apple"
	fmt.Println(m3)
	//获取值
	fmt.Println(m3["pc"])
	//多个参数，ok标记是否找到结果
	searchResult, ok := m3["phone"]
	if ok {
		fmt.Println(searchResult)
	} else {
		fmt.Println("not found phone")
	}
	//修改
	m3["pc"] = "intel"
	fmt.Println(m3)
	//迭代
	for key, value := range m3 {
		fmt.Println(key, value)
	}
	//删除
	delete(m3, "phone")
	fmt.Println(m3)
}

// MapCopyTest 深拷贝第一种
func MapCopyTest() {
	m3 := make(map[string]string)
	m3["pc"] = "amd"
	m3["phone"] = "apple"
	newMap := make(map[string]string, len(m3))
	for key, value := range m3 {
		newMap[key] = value
	}
	fmt.Println(m3, newMap)
	delete(m3, "pc")
	fmt.Println(m3, newMap)
}

// MapCopyJson 使用json完成拷贝
func MapCopyJson() {
	m3 := make(map[string]string)
	m3["pc"] = "amd"
	m3["phone"] = "apple"
	newMap := make(map[string]string, len(m3))
	//jsonData是字节数组
	jsonData, err := json.Marshal(m3)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(jsonData))
	err = json.Unmarshal(jsonData, &newMap)
	if err != nil {
		panic(err)
	}
	fmt.Println(newMap)
}

func MapSliceTest() {
	var s []map[string]string
	intel := map[string]string{"cpu": "ultra 7 265k", "memory": "48G", "gpu": "B580"}
	amd := map[string]string{"cpu": "9900x", "memory": "48G", "gpu": "5070"}
	apple := map[string]string{"cpu": "m4", "memory": "16G", "gpu": "igpu"}
	s = append(s, intel, amd, apple)
	//map的存储是无序的
	fmt.Println(s)
	for key, value := range s {
		fmt.Printf("第%d个数据\n", key)
		for k, data := range value {
			fmt.Println(k, data)
		}
	}
}

func MapMapTest() {
	m1 := make(map[string]map[string]string)
	intel := map[string]string{
		"cpu": "ultra 7 265k", "memory": "48G", "gpu": "B580",
	}
	m1["intel"] = intel
	fmt.Println(m1["intel"]["cpu"])
}
